package com.example.product.presentationViews;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.example.presentation_libary.presentationViews.BasePresentionView;
import com.example.product.Constants;
import com.example.product.Data;
import com.example.productmodule.R;

import java.io.File;
import java.io.FileFilter;
import java.util.List;

import wseemann.media.FFmpegMediaMetadataRetriever;

/**
 * 我是视频的
 */
public class DislayVideoView extends BasePresentionView {
    public static final String Tag = "辅屏视频页";
    VideoView videoView;
    List<File> files;

    public DislayVideoView(@NonNull Context context, String mjson) {
        super(context, mjson);
    }

    @Override
    public int getLayoutId() {
        return R.layout.view_auxiliary_video;
    }

    public void initEvent() {
        TextView videoTv = rootView.findViewById(R.id.tv_video_content);
        TextView videoStatus = rootView.findViewById(R.id.tv_video_status);
        Data data = GsonUtils.fromJson(json, Data.class);
        Log.i("==DislayVideoView==", json);
        videoTv.setText("商品货道-" + data.getName());
        videoView = rootView.findViewById(R.id.adv_video);
        img_video_adv = rootView.findViewById(R.id.img_video_adv);
        if (FileUtils.isDir(Constants.DIR_AUXILIARY)) {
            files = getFiles(data.getName() + "-");
            if (files.size() > 0) {

                setDataVideo(videoView, files);

            } else {
                videoView.setVisibility(View.GONE);
                videoStatus.setText("暂无视频");
            }
        } else {
            Log.i(Tag, "文件路径= 不存在");
        }

    }

    /**
     * 查询文件夹下的所有文件 及进行条件过滤
     *
     * @param str_fixe
     * @return
     */
    public List<File> getFiles(final String str_fixe) {
        List<File> files = FileUtils.listFilesInDirWithFilter(Constants.DIR_AUXILIARY, new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                boolean contains = pathname.getName().startsWith(str_fixe) && isVideo(pathname.getName());
                return contains;
            }
        });
        Log.i(Tag, "文件数量=" + files.size() + "");
        return files;
    }

    /**
     * 判断后缀名是否是图片格式
     *
     * @param pathname
     * @return
     */
    public boolean isVideo(String pathname) {
        if (pathname.endsWith(".mp4") || pathname.endsWith(".avi")) {
            return true;
        }
        return false;
    }


    int videoIndex = 0;
    int bitmapIndex;
    Bitmap bitmap = null;
    ImageView img_video_adv;

    public void setDataVideo(final VideoView videoPlayer, final List<File> playList) {
        startVideo(videoPlayer, playList);
        videoPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                ++videoIndex;
                if (videoIndex < playList.size()) {

                } else {
                    videoIndex = 0;
                }
                Log.i(Tag, "=加载视频中=" + mediaPlayer.getCurrentPosition());
                startVideo(videoPlayer, playList);
            }
        });
    }

    public Uri getUri(List<File> playList) {
        Uri newUri = FileProvider.getUriForFile(mContext.getApplicationContext(),
                mContext.getPackageName() + ".fileprovider",
                playList.get(videoIndex));
        return newUri;
    }

    public Uri getBitmapUri(List<File> playList) {
        Uri newUri = FileProvider.getUriForFile(mContext.getApplicationContext(),
                mContext.getPackageName() + ".fileprovider",
                playList.get(bitmapIndex));
        return newUri;
    }

    public void startVideo(final VideoView videoPlayer, List<File> playList) {
        if (bitmap == null) {
            getfirstBitmap();
        }
        img_video_adv.setVisibility(View.VISIBLE);
        videoPlayer.setVideoURI(getUri(playList));
        videoPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(final MediaPlayer mp) {
                mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {
                        Log.i(Tag, "=加载视频中=" + what);
                        img_video_adv.setVisibility(View.GONE);
                        getfirstBitmap();
                        return false;
                    }
                });
                mp.start();
            }
        });
    }

    public void getfirstBitmap() {
        try {
            //截取视频中的第一帧的图像
            final FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
            mmr.setDataSource(mContext, getBitmapUri(files));
            mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ALBUM);
            mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ARTIST);
            ThreadUtils.executeByCpu(new ThreadUtils.SimpleTask<Bitmap>() {
                @Override
                public Bitmap doInBackground() throws Throwable {
                    bitmap = mmr.getFrameAtTime(1000000, FFmpegMediaMetadataRetriever.OPTION_CLOSEST); // frame at 2 seconds
                    return bitmap;
                }

                @Override
                public void onSuccess(Bitmap result) {
                    img_video_adv.setImageBitmap(result);
                    mmr.release();
                    ++bitmapIndex;
                    if (bitmapIndex >= files.size()) {
                        bitmapIndex = 0;
                    }
                }
            });
        } catch (Exception e) {
            Log.i(Tag, "=视频地址有问题=" + e.toString());
        }
    }
}
